package org.openfans.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openfans.domain.Auth;
import org.openfans.domain.Facade;
import org.openfans.domain.Fans;
import org.openfans.util.EncryptUtil;
import org.springframework.mail.MailSender;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class RegistFormController extends SimpleFormController {
	private Facade facade = null;

	private MailSender mailSender = null;

	public void setMailSender(MailSender mailSender) {
		this.mailSender = mailSender;
	}

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	public RegistFormController() {
		setCommandName("auth");
		setCommandClass(Auth.class);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		Auth auth = (Auth) command;
		auth.setPasswd(EncryptUtil.encode(auth.getPasswd()));
		auth.setCode(EncryptUtil.genActivateCode());
		facade.save(auth);
		//
		// SimpleMailMessage smm = new SimpleMailMessage();
		// smm.setFrom("openfans@openfans.org");
		// smm.setTo(auth.getEmail());
		// smm.setSubject("��ӭ4��openfans���ͥ");
		// smm.setText("��ã�����http://www.openfans.org/activate.html?code="
		// + auth.getCode());
		//		
		// try {
		// mailSender.send(smm);
		// } catch (Exception e) {
		// e.printStackTrace();
		// �����ʼ�ʧ�ܣ���ֱ�Ӱ�ע���û�����
		String name = request.getParameter("permenent_name");

		Fans fans = new Fans();
		fans.setEmail(auth.getEmail());
		fans.setNickName(auth.getName());
		fans.setJoinDate(new Date());
		fans.setIcon("images/defaultFans.gif");
		// 如果name栏不为空，就表示用户同意用它做自己的permenent link
		if (!"".equals(name)) {
			fans.setName(name);
			fans.setStatus(Fans.STATUS_PERMENENT);
		} else {
			// 设置一个uniqe的值，先用这个做，会有隐患
			fans.setName(String.valueOf(System.currentTimeMillis()));
		}
		facade.save(fans);
		auth.setFans(fans);
		facade.save(auth);
		// 放入session
		request.getSession().setAttribute("loginFans", fans);
		// }

		return new ModelAndView(getSuccessView());
	}
}
